package com.df.ez_game.server.logic;

import com.alibaba.fastjson2.JSON;
import com.df.ez_game.server.IEzGameMsgCodec;
import com.df.ez_game.server.msg.client.ClientReqMsg;
import com.df.ez_game.server.msg.client.ClientRespMsg;
import com.df.ez_game.tools.EzConstant;

import java.nio.charset.StandardCharsets;

public class JsonCodec implements IEzGameMsgCodec {
    @Override
    public byte[] encodeNetMsg(ClientRespMsg resp) {

        try {
            String jsonString = JSON.toJSONString(resp);
            byte[] bytes = jsonString.getBytes(StandardCharsets.UTF_8);
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return EzConstant.ProtoConstant.emptyBytes;
    }

    @Override
    public ClientReqMsg decodeNetMsg(byte[] reqBytes) {

        try {
            String str = new String(reqBytes,StandardCharsets.UTF_8);
            ClientReqMsg msg = JSON.parseObject(str, ClientReqMsg.class);
            return msg;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public byte[] encodeBusinessMsg(Object resp,Class clazz) {
        if(resp==null){
            return EzConstant.ProtoConstant.emptyBytes;
        }
        try {
            String jsonString = JSON.toJSONString(resp);
            byte[] bytes = jsonString.getBytes(StandardCharsets.UTF_8);
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return EzConstant.ProtoConstant.emptyBytes;
    }

    @Override
    public Object decodeBusinessMsg(byte[] reqBytes,Class clazz) {
        try {
            String str = new String(reqBytes,StandardCharsets.UTF_8);
            Object msg = JSON.parseObject(str, clazz);
            return msg;
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }
}
